//
//  NetUtls.m
//  ContinueEDUPhone
//
//  Created by SL on 13-11-25.
//  Copyright (c) 2013年 Sheng Long. All rights reserved.
//

#import "NetUtls.h"
#import "z_Network.h"

#import "NationClass.h"

@implementation NetUtls

//获取当前的网络状态
+ (int)getNetworkState
{
    struct sockaddr_in zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // 以下objc相关函数、类型需要添加System Configuration 框架
    // 用0.0.0.0来判断本机网络状态
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability,&flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
        return -1;
    }
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? 1 : 0;
}

//get方法请求   need是否需要帮助检查网络
+(ASIHTTPRequest *)httpGet:(id)delegate withValue:(NSDictionary *)dic tag:(NSInteger)tag need:(BOOL)need
{
    [NationClass saveNationData];
    
#pragma mark - 上传数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (!CURRENT_NETWORK_STATE && tag==IOS_UPLOAD_TAG) {
        //没有网络上传数据,保存要上传的数据
        [defaults setValue:[dic JSONString] forKey:@"IOS_UPLOAD_TAG"];
    }
    if (CURRENT_NETWORK_STATE) {
        if (tag != IOS_UPLOAD_TAG && [defaults valueForKey:@"IOS_UPLOAD_TAG"]){
            NSString *upload = [defaults valueForKey:@"IOS_UPLOAD_TAG"];
            [[z_Network httpGet:[upload objectFromJSONString] Url:IOS_WEBURL Delegate:nil Tag:IOS_UPLOAD_TAG] startAsynchronous];
        }
        [defaults removeObjectForKey:@"IOS_UPLOAD_TAG"];
    }
#pragma mark
    
    if (!CURRENT_NETWORK_STATE && need) {
        [LoadingFrameView autoDisappearTipview:@"请检查网络连接"];
        return nil;
    }
    ASIHTTPRequest *request = [z_Network httpGet:dic Url:IOS_WEBURL Delegate:delegate Tag:tag];
    return request;
}

//Post方法请求
+(ASIHTTPRequest *)httpPost:(id)delegate withValue:(NSDictionary *)dic tag:(NSInteger)tag need:(BOOL)need
{
    if (!CURRENT_NETWORK_STATE && need) {
        [LoadingFrameView autoDisappearTipview:@"请检查网络连接"];
        return nil;
    }
    ASIHTTPRequest *request = [z_Network httpPostValue:dic Url:IOS_WEBURL Delegate:delegate Tag:tag];
    return request;
}

@end
